Json = Json or require("common.Json")
local Config = require("Config")
local CommonDefine = require("common.CommonDefine")
local Log = require("common.Log")
local CommonDB = require("common.CommonDB")
local LogDefine = require("common.LogDefine")
local Msg = require("core.Msg")
local ObjHuman = require("core.ObjHuman")
local CreateRole = require("role.CreateRole")
local PlatformDefine = require("platform.Define")
local PfLogic = require("platform.PfLogic")
local LuaMongo = _G.lua_mongo
local DB = require("common.DB")
local RoleDBLogic = require("role.RoleDBLogic")
local Util = require("common.Util")
local AuthCheck = require("scene.AuthCheck")


function CG_AA_DISCONNECT(human)
	if type(human) ~= "table" then return end
	ObjHuman.doDisconnect(human, CommonDefine.DISCONNECT_NORMAL)
end

function setLoginParams(human, msg, params)
	human.lang = msg.lang
	human.region = (msg.region == "") and "CN" or string.upper(msg.region) 
	human.ip = (msg.ip ~= "") and msg.ip or _G.global.get_ip_from_fd(human.fd)

	-- 有些字段重复赋值，看看以后要不要干掉。。。
	human.pf = params.pf
	human.isIOS = params.isIOS or 0
	human.vopenid = params.openid or ""
	human.openkey = params.openkey or ""
	human.phpChanelID = params.phpChanelID or ""
	human.appid = params.appid
    human.gameName = params.gameName or ""
    human.version = params.version or nil

	human.pf_info = human.pf_info or {}
	human.pf_info.openid = params.openid or ""
	human.pf_info.openkey = params.openkey or ""
	human.pf_info.pf = params.pf or ""
	human.pf_info.pfkey = params.pfkey or ""
	human.pf_info.zoneid = params.zoneid or 0
	human.pf_info.serverid = params.serverid or 0
	human.pf_info.tcTime = os.time()	
	human.pf_info.lvYellow = params.lvYellow or 0
	human.pf_info.yearYellow = params.yearYellow or 0
	human.pf_info.superYellow = params.superYellow or 0
	human.pf_info.lvBlue = params.lvBlue or 0
	human.pf_info.yearBlue = params.yearBlue or 0
	human.pf_info.superBlue = params.superBlue or 0
	human.pf_info.validTimeBlue = params.validTimeBlue or 0
	human.pf_info.vipSevenk = params.vipSevenk or 0
	human.pf_info.validTimeSevenk = params.validTimeSevenk or 0
	human.pf_info.phpChanelID = params.phpChanelID or ""
	human.pf_info.phoneSystem = params.phoneSystem or "android"
	human.pf_info.from_openid = params.from_openid or ""
end

function sendDisconnect(fd, errCode)
	local mm = Msg.gc.GC_DISCONNECT
	mm.code = errCode
	mm.msg = CommonDefine.DISCONNECT_MSG[errCode]
	Msg.send(mm, fd)
end

function CG_ASK_LOGIN(fd, msg)
	if _G.is_middle == true then return end

	--判断是否是数字类型
	if type(fd) ~= "number" then
		assert()
	end
	print("CG_ASK_LOGIN", msg.account)

	--如果在线人数大于最大可容纳在线人数时，断开链接
	local onlineCnt = ObjHuman.getOnlineCnt()
	if onlineCnt >= CommonDefine.MAX_ONLINE_COUNT then		
		return sendDisconnect(fd, CommonDefine.DISCONNECT_MAX_ONLINE)
	end

    local retAuth = AuthCheck.authCheck(msg.account, msg.authkey, msg.timestamp, msg.ip)
	if retAuth ~= true then
		return sendDisconnect(fd, CommonDefine.DISCONNECT_AUTH_FAIL)
	end

	local account = msg.account
	local params = Json.Decode(msg.params)	
	--如果是已经登录的，也断开连接 九 零 一 起玩 www. 9 01  7 5.com 
	local human_old = ObjHuman.onlineAccount[account]
	if human_old then
		ObjHuman.doDisconnect(human_old, CommonDefine.DISCONNECT_DUPLICATE)
	end		

	--创建新角色
	local human = ObjHuman.create(fd, account, human_old and human_old.db, nil)
	setLoginParams(human, msg, params) -- 设置登录参数

	if human.db == nil then
		-- 新号
        local ip,time = CommonDB.getBanIp(msg.ip)
        if (time and time > os.time()) then
            ObjHuman.doDisconnect(human, CommonDefine.DISCONNECT_BANIP)
			return
        else
            CommonDB.delBanIp(msg.ip)
        end
		
		Log.write(Log.LOGID_OSS_CREATELOSS,account, "", LogDefine.HUMAN_LOST.ENTRANCE, human.ip, human.pf, human.appid, human.phpChanelID)
		CreateRole.createNewRole(human)
	else
		-- 封号
		if human.db.banUserTime == -1 or 
			(human.db.banUserTime and human.db.banUserTime > os.time()) then
			ObjHuman.doDisconnect(human, CommonDefine.DISCONNECT_BANUSER)
			return
		end

        local ip,time = CommonDB.getBanIp(msg.ip)
        if (time and time > os.time()) then
			ObjHuman.doDisconnect(human, CommonDefine.DISCONNECT_BANIP)
			return
        else
            CommonDB.delBanIp(msg.ip)
        end
		ObjHuman.onLogin(human, nil)
	end	
end

function CG_HEART_BEAT(human, msg)
	local msgRet = Msg.gc.GC_HEART_BEAT
	msgRet.timeStamp = os.time()
	Msg.send(msgRet, human.fd)
end


-- 记录fps
local FPS_TB = {["guaji"]=1, ["zhandou"]=1, ["zhucheng"]=1, ["buzhen"]=1}
function CG_PHONE_FPS(human, msg)
    if FPS_TB[msg.fpsType] == nil then return end

    human.db.fpsTb = human.db.fpsTb or {}
    human.db.fpsTb[msg.fpsType] = { lv = human.db.lv, startFps = msg.startFps, endFps = msg.endFps}
end


function CG_HEART_BEAT_M(human)

end

function CG_ASK_DISCONNECT(human)
    ObjHuman.doDisconnect(human, CommonDefine.DISCONNECT_NORMAL)
end

function CG_CLIENT_ERROR(human, msg)
	Log.write(Log.LOGID_OSS_CLIENT_ERR, human.db and human.db._id or "", human.db and human.db.account or human.account, human.db and human.db.name or "", msg.err)
end

function CG_CLIENT_LOAD_ERROR(human, msg)
	Log.write(Log.LOGID_OSS_CLIENT_LOAD_ERR, human.db and human.db._id or "", human.db and human.db.account or human.account, human.db and human.db.name or "", msg.err)
end


IOS_FLAG_CHARGECLOSE = 0 	-- 提示关闭
IOS_FLAG_CHARGEOPENTIP = 1 	-- 提示开放
IOS_FLAG_CHARGEOPEN = 2 	-- 充值开放

function getIosChargeOpenFlag(human)
	if PfLogic.isFkwTishen() == true then
		if human.isIOS == 1 then
			return IOS_FLAG_CHARGECLOSE
		end
	end
	
	if PfLogic.isKunTangTishen() == true then
		return IOS_FLAG_CHARGECLOSE
	end
	
	return IOS_FLAG_CHARGEOPEN 
end

function canCharge(human)
	if getIosChargeOpenFlag(human) == IOS_FLAG_CHARGECLOSE then
		return
	end
	return true
end